package ar.uba.dc.tl.mylanga.inputhandler;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.PushbackReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

public class FileInputHandler extends InputHandler {

	public FileInputHandler(Input input) {
		super(input);
	}

	@Override
	public void checkArguments() {
		List<String> arguments = this.getArguments();

		if (arguments == null || arguments.size() < 2) {
			throw new RuntimeException("invalid arguments");
		}

		String filename = arguments.get(1).trim();

		if (filename.isEmpty()) {
			throw new RuntimeException("invalide file name");
		}
	}

	private String getFilename() {
		this.checkArguments();

		String filename = this.getArguments().get(1).trim();

		return filename;
	}

	@Override
	public PushbackReader getReader() {
		String filename = this.getFilename();

		try {
			return new PushbackReader(
					new BufferedReader(
							new InputStreamReader(
									new FileInputStream(filename), "UTF8")), InputHandler.PUSH_BACK_SIZE
			);
		} catch (FileNotFoundException e) {
			throw new RuntimeException("file not found", e);
		} catch (UnsupportedEncodingException e) {
			throw new RuntimeException("error creating reader", e);
		}
	}
}
